import { defineStore } from "pinia";
import { to } from "await-to-js";
import { ref, computed } from "vue";
import type { LoginData, UserInfoVo } from "@/api/user/types";
import {
  login as loginApi,
  getInfo as getUserInfo,
  logout as logoutApi,
  updUserInfo as updUserInfoApi,
} from "@/api/user/user";
import defaultAvatarImg from "@/assets/img/home/data-head.jpg";

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref();
    const isLogin = computed(() => !!token.value);
    const userInfo = ref<UserInfoVo>();
    const defaultAvatar = defaultAvatarImg;

    /**
     * 登录
     * @param userInfo
     * @returns
     */
    const login = async (userInfo: LoginData): Promise<void> => {
      const [err, res] = await to(loginApi(userInfo));
      if (res) {
        const data = res.data;
        token.value = data.access_token;
        return Promise.resolve();
      }
      return Promise.reject(err);
    };

    // 获取用户信息
    const getInfo = async (): Promise<void> => {
      const [err, res] = await to(getUserInfo());
      if (res) {
        userInfo.value = res.data;
        return Promise.resolve();
      }
      return Promise.reject(err);
    };

    // 修改用户信息
    const updUserInfo = async (updUserInfo: UserInfoVo): Promise<void> => {
      const [err, res] = await to(updUserInfoApi(updUserInfo));
      if (res) {
        userInfo.value = updUserInfo;
        return Promise.resolve();
      }
      return Promise.reject(err);
    };

    // 注销
    const logout = async (): Promise<void> => {
      await logoutApi();
      token.value = undefined;
      userInfo.value = undefined;
    };

    const reset = () => {
      userInfo.value = null; // 清空用户信息
      token.value = ""; // 清空 token
    };

    return {
      token,
      isLogin,
      userInfo,
      defaultAvatar,
      login,
      getInfo,
      updUserInfo,
      logout,
      reset,
    };
  },
  {
    persist: true,
  }
);
